﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace ServicoBase
{
    public class UnityInstanceProvider : IInstanceProvider
    {
        private Type _serviceType;
        private IUnityContainer _container;
        private string _nomeContainer;

        public UnityInstanceProvider(Type serviceType)
        {
            this._serviceType = serviceType;

            _container = new UnityContainer();

            _nomeContainer = DadosFila.ObterNomeContainer();

            instanciarContainer();
        }

        private void instanciarContainer()
        {
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Configure(_container, _nomeContainer);
        }

        private void carregarContainer(string nomeContainer) 
        {
            _container.LoadConfiguration(nomeContainer);
        }

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
        {
            string _nomeContainerNovo = DadosFila.ObterNomeContainer();
            if (!_nomeContainerNovo.Equals(_nomeContainer)) 
            {
                carregarContainer(_nomeContainerNovo);
            }

            return _container.Resolve(_serviceType);
        }

        public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
        {
            if (instance is IDisposable)
                ((IDisposable)instance).Dispose();
        }
    }
}